﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;

namespace GameForKids
{
    class FindSoundGamePlay : DrawableGameComponent
    {
        // bien dem thoi gian
        public float milisecon = 0;
        // hien thi thoi gian choi
        public string timePlay = "";
        public int moved = 0;
        private SpriteFont helpFont;

        private SpriteFont font;


        // Game Object
        public int Level = 1;
        public List<Couple> Couples;

        public SoundEffect soundClick;
        public SoundEffect soundCorrect;

        // cong thuc tinh diem
        public static string CongThucGoc = "40-T-N";
        public static string CongThucHienTai = "";

        public void Reset(int _level)
        {
            Couples = new List<Couple>();
            Level = _level;
            List<Vector2> positions = new List<Vector2>();
            positions.Add(new Vector2(190, 125));
            positions.Add(new Vector2(390, 125));
            positions.Add(new Vector2(590, 125));
            positions.Add(new Vector2(190, 305));
            positions.Add(new Vector2(390, 305));
            positions.Add(new Vector2(590, 305));

            for (int i = 1; i <= 6; i++)
            {
                int value = i + (_level - 1)*6;
                int r = Suport.Random.Next(1,positions.Count+1) -1;
                Couples.Add(new Couple("FindSoundGame/Images/" + value, "FindSoundGame/Sounds/" + value, positions[r]));
                positions.RemoveAt(r);
            }

            int index = Suport.Random.Next(1, Couples.Count + 1) - 1;
            Couples[index].IsWaitToCheck = true;
            Couples[index].OnRunTime = true;
        }


        // tao co so du lieu
        private string strConnectionString = @"isostore:/FindSoundGameDB.sdf";
        public FindSoundGamePlay(Game game)
            : base(game)
        {
            font = this.Game.Content.Load<SpriteFont>("Fonts/ChartFont");

            helpFont = this.Game.Content.Load<SpriteFont>("Fonts/HelpFont");
            soundClick = this.Game.Content.Load<SoundEffect>("FindSoundGame/Sounds/Click");
            soundCorrect = this.Game.Content.Load<SoundEffect>("FindSoundGame/Sounds/Correct");
            
            // tao csdl
            using (ReadAndWrite readAndWriteDB = new ReadAndWrite(strConnectionString))
            {
                if (readAndWriteDB.DatabaseExists() == false)
                {
                    readAndWriteDB.CreateDatabase();
                }
            }


            // lay cong thuc
            using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isolatedStorageFile.FileExists("CongThuc" + GameForKids.gameState.ToString() + ".txt"))
                {
                    using (IsolatedStorageFileStream isfs = isolatedStorageFile.OpenFile("CongThuc" + GameForKids.gameState.ToString() + ".txt", FileMode.Open))
                    {
                        using (StreamReader reader = new StreamReader(isfs))
                        {
                            while (!reader.EndOfStream)
                            {
                                CongThucHienTai = reader.ReadLine();
                            }
                        }
                    }
                }
            }
            if (CongThucHienTai == "" || CongThucHienTai == null)
                CongThucHienTai = CongThucGoc;

            Reset(1);
        }
     
        // luu theo dang ID - ten  - level - diem - ngay
        public void saveScore(int _score)
        {
            using (ReadAndWrite readAndWriteDB = new ReadAndWrite(strConnectionString))
            {
                DataScore newscore = new DataScore { ID = DateTime.Now.ToString(),
                    name = GameForKids.userName,
                    level = FindSoundGame.level,
                    score = _score,
                    day = DateTime.Today.ToShortDateString() };
                readAndWriteDB.TableScore.InsertOnSubmit(newscore);
                readAndWriteDB.SubmitChanges();
            }
        }

        private IList<DataScore> getListDataScore(string _name, int _level)
        {
            IList<DataScore> listDataScore = null;
            using (ReadAndWrite readAndWrite = new ReadAndWrite(strConnectionString))
            {
                IQueryable<DataScore> dataScoreQuery = from data in readAndWrite.TableScore where data.name.Equals(_name) && data.level == _level select data;
                listDataScore = dataScoreQuery.ToList();
            }
            return listDataScore;
        }

        public void startNewLevel(int _level)
        {
            ChartScreen.listDataScore = this.getListDataScore(GameForKids.userName, _level);
            ChartScreen.levelOfGame = _level;
            // cho tat ca cac cell lat up lai khi qua man moi
            Level = _level;
            Reset(_level);
            moved = 0;
            milisecon = 0;
        }

    

        //tinh diem
        public int getScore()
        {
            int mark = 0;
            XuLyCongThuc xulycongthuc;
            string s = "";

            xulycongthuc = new XuLyCongThuc();
            s = xulycongthuc.TinhDiem(CongThucHienTai, moved, (int)(milisecon / 1000), FindCharactersGame.level);
            double d = double.Parse(s);
            mark = (int)d;

            if (mark >= 10)
                return 10;
            if (mark <= 0)
                mark = 0;
            return mark;
        }

        public void doOnReplayClick()
        {
            foreach (Couple couple in Couples)
            {
                if (couple.IsWaitToCheck == true)
                {
                    if (couple.OnPlay == false)
                    {

                            Suport.GetSound(couple.SoundLink).Play();
                        couple.OnPlay = true;
                    }
                }
            }
        }

   
        public bool checkComplete()
        {
            if (Couples.Count == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public override void Initialize()
        {
            base.Initialize();
        }

        public void setTimePlay()
        {
            timePlay = ((int)milisecon / 60000).ToString() + " : " + (((int)milisecon / 1000) % 60).ToString();
        }

        public override void Update(GameTime gameTime)
        {
            float elapsed = (float)gameTime.ElapsedGameTime.Milliseconds;
            milisecon += elapsed;
            setTimePlay();          

            int index = -1;
            for (int i = 0; i < Couples.Count; i++ )
            {
                Couples[i].Update(gameTime);
                if (Couples[i].IsShow == false)
                {
                    index = i;
                }

                if (Couples[i].OnRunTime == true)
                {
                    if (Couples[i].TimeForPlay < 0.0f)
                    {
                        Couples[i].OnRunTime = false;
                        Couples[i].TimeForPlay = 2.0f;
                        Couples[i].IsWaitToCheck = true;
                            Suport.GetSound(Couples[i].SoundLink).Play();
                    }
                }
            }

            if (index != -1)
            {
                Couples.RemoveAt(index);
                if (Couples.Count != 0)
                {
                    Couples[Suport.Random.Next(1, Couples.Count + 1) - 1].OnRunTime = true;
                }
            }

            base.Update(gameTime);
        }

        public virtual void Draw(GameTime gametime, SpriteBatch spriteBatch)
        {
            foreach (Couple couple in Couples)
            {
                couple.Draw(spriteBatch);
            }
            spriteBatch.DrawString(helpFont, timePlay, new Vector2(10, 250), Color.White);
            spriteBatch.DrawString(helpFont, moved.ToString(), new Vector2(10, 300), Color.White);

        }

        public void TouchEvent(TouchLocation touch)
        {

            foreach (Couple couple in Couples)
            {
                if (couple.CheckTouch(touch) == true)
                {
                    if (couple.OnClick == false)
                    {
                        if (GameForKids.ISMUSIC)
                        {
                            soundClick.Play();
                        }
                        moved++;

                        couple.OnClick = true;
                    }
                    if (couple.IsWaitToCheck == true)
                    {
                        if (couple.IsShow == true)
                        {
                            if (GameForKids.ISMUSIC)
                            {
                                soundCorrect.Play();
                            }


                        }

                        couple.IsShow = false;
                    }
                }
            }
        }
    }
}
